﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using G.Reader.Data;
using G;
using G.Navigate;
using System.Xml;
//using System.ServiceModel.Syndication;
using System.Text.RegularExpressions;
using Microsoft.Phone.Shell;
using G.Animation;

namespace G.Reader
{
    public partial class MainPage : GBasePage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            //G.Reader.Utils.PushHelp.CreatePush();
            if (listbox_books.ItemsSource == null)
                listbox_books.LayoutUpdated += new EventHandler(listbox_books_LayoutUpdated);
            listbox_books.ItemsSource = GloabalData.Instance.BookDataBase.BookTable.ToList();
            List<LogData> logs = LogData.ReadLogData();
            if (logs != null && logs.Count > 0)
            {
                if (MessageBox.Show("上次的退出非正常退出，是否报告异常信息？", "提示", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    foreach (var item in logs)
                    {
                        Microsoft.Phone.Tasks.EmailComposeTask task = new Microsoft.Phone.Tasks.EmailComposeTask();
                        task.Body = item.Date.ToString() + "\r\n" + item.Message;
                        task.Subject = item.Title;
                        task.To = "haiwei.gong@yek.me";
                        task.Show();
                        break;
                    }
                    LogData.Clear();
                }
            }
        }

        void listbox_books_LayoutUpdated(object sender, EventArgs e)
        {
            if (this.listbox_books.GetScrollHost() != null)
            {
                listbox_books.LayoutUpdated -= listbox_books_LayoutUpdated;
                var listItems = this.listbox_books.GetItemsInView().ToList();
                var peelList = new FrameworkElement[] { ApplicationTitle, PageTitle }.Union(listItems);
                peelList.Peel(null, Directions.In);
            }


        }

        void media_CurrentStateChanged(object sender, RoutedEventArgs e)
        {

        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            base.OnBackKeyPress(e);
            if (slideup_add.IsOpen)
            {
                slideup_add.IsOpen = false;
                e.Cancel = true;
            }

            if (!e.Cancel)
            {
                e.Cancel = true;
                var listItems = this.listbox_books.GetItemsInView().ToList();
                var peelList = new FrameworkElement[] { ApplicationTitle, PageTitle }.Union(listItems);
                peelList.Peel(() =>
                {
                    G.Common.ExitApplication(Application.Current);
                });
                //G.Animation.MetroInMotion.Peel(
            }
        }

        ItemFlyInAndOutAnimations ItemFlyInAndOutAnimations = new ItemFlyInAndOutAnimations();
        private void listbox_books_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (listbox_books.SelectedItem != null)
            {
              

                ItemFlyInAndOutAnimations.ItemFlyOut(this.listbox_books.ItemContainerGenerator.ContainerFromItem(listbox_books.SelectedItem) as FrameworkElement, () =>
                {
   
                });
                BookInfo book = listbox_books.SelectedItem as BookInfo;
                switch (book.BookType)
                {
                    case BookType.TXT:
                        this.NavigationService.Navigate(new Uri("/View/BookPage.xaml?bookid=" + book.ID, UriKind.Relative));
                        break;
                    case BookType.RSS:
                        this.NavigationService.Navigate(new Uri("/View/RSSListPage.xaml?bookid=" + book.ID, UriKind.Relative));
                        break;
                    case BookType.News:

                        FeedItem item = new FeedItem();
                        item.Content = GloabalData.Instance.BookDataBase.ReadBookAll(book);
                        item.Link = new Uri(book.Address);
                        item.Title = book.BookName;
                        this.NavigationService.Navigate("/View/RSSDetailPage.xaml", item);
                        break;
                }
                this.listbox_books.SelectedItem = null;

            }
        }

        private void SignInButton_SessionChanged(object sender, Microsoft.Live.Controls.LiveConnectSessionChangedEventArgs e)
        {
            if (e.Session != null)
            {
                GloabalData.Instance.Session = e.Session;
                this.NavigationService.Navigate("/View/FoldersPage.xaml");
            }
            this.UnregisterLoading();
            this.IsEnabled = true;
        }


        private void menuDelete_Click(object sender, RoutedEventArgs e)
        {
            MenuItem menu = sender as MenuItem;
            if (MessageBox.Show("确定要删除这本书吗？", "提示", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                GloabalData.Instance.BookDataBase.DeleteBook(menu.DataContext as BookInfo);
                listbox_books.ItemsSource = GloabalData.Instance.BookDataBase.BookTable.ToList();
            }
        }

        private void slideup_add_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            slideup_add.IsOpen = false;
            if (slideup_add.SelectedIndex != -1)
            {
                switch (slideup_add.SelectedIndex)
                {
                    case 0:
                        if (GloabalData.Instance.Session == null)
                        {
                            this.RegisterLoading(null);
                            System.Windows.Automation.Peers.ButtonAutomationPeer bam = new System.Windows.Automation.Peers.ButtonAutomationPeer(btnlogin);
                            System.Windows.Automation.Provider.IInvokeProvider iip = bam.GetPattern(System.Windows.Automation.Peers.PatternInterface.Invoke) as System.Windows.Automation.Provider.IInvokeProvider;
                            iip.Invoke();
                            this.IsEnabled = false;
                        }
                        else
                            this.NavigationService.Navigate(new Uri("/View/FoldersPage.xaml", UriKind.Relative));
                        break;
                    case 1:
                        this.NavigationService.Navigate(new Uri("/View/RSSListPage.xaml", UriKind.Relative));
                        break;
                    default:
                        break;
                }

                slideup_add.SelectedIndex = -1;
            }
        }
        private void btnAdd_Click(object sender, EventArgs e)
        {
            slideup_add.IsOpen = !slideup_add.IsOpen;
        }

        private void Test()
        {

        }

        private void btnChat_Click(object sender, EventArgs e)
        {
            //Utils.PageOperateUtils.ValidatIsLogin(isLogin =>
            //{
            //    if (isLogin)
            //    {
            //        this.NavigationService.Navigate(new Uri("/View/ChatPage.xaml", UriKind.Relative));
            //    }
            //}, true);

        }

        private void addReader_Click(object sender, RoutedEventArgs e)
        {

        }

        private void tileLogin_Click(object sender, RoutedEventArgs e)
        {
            //if (GloabalData.Instance.User == null)
            //{
            //    Utils.PageOperateUtils.ValidatIsLogin(isLogin =>
            //    {

            //    }, false);
            //}
            //else
            //{
            //    if (MessageBox.Show("确定要退出登录吗？", "提示", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            //        GloabalData.Instance.User = null;
            //}
        }

        private void tileSettings_Click(object sender, RoutedEventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/View/SettingsPage.xaml", UriKind.Relative));
        }

        private void tileMessage_Click(object sender, RoutedEventArgs e)
        {
            //Utils.PageOperateUtils.ValidatIsLogin(isLogin =>
            //{
            //    if (isLogin)
            //    {
            //        this.NavigationService.Navigate(new Uri("/View/Message/MessagePage.xaml", UriKind.Relative));
            //    }
            //}, true);
        }

        private void tileMap_Click(object sender, RoutedEventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/View/Map/MapPage.xaml", UriKind.Relative));
        }

        private void btnSetting_Click(object sender, EventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/View/SettingsPage.xaml", UriKind.Relative));
        }
        //TileFlipAnimation tile;
        //private void listbox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        //{
        //    if (tile == null)
        //        tile = new TileFlipAnimation(this.listbox1, this);
        //    tile.Duration = 250;
        //    tile.Angle = 50;
        //    tile.FeatherDelay = 500;
        //    tile.Direction = Directions.Out;
        //    tile.HoldSelectedItem = true;
        //    var st = tile.Story();
        //    st.Completed += new EventHandler(st_Completed);
        //    st.Begin();
        //}

        //void st_Completed(object sender, EventArgs e)
        //{
        //    tile. Duration = 350;
        //    tile.Angle = -80;
        //    tile.FeatherDelay = 50;
        //    tile.Direction = Directions.In;
        //    tile.HoldSelectedItem = false;
        //    tile.Story().Begin();
        //}





    }
}